package com.tonann.app.utils;

import com.alibaba.fastjson2.JSONArray;
import com.tonann.app.domain.AppSensor;
import com.tonann.common.constant.CacheConstants;
import com.tonann.common.core.redis.RedisCache;
import com.tonann.common.utils.StringUtils;
import com.tonann.common.utils.spring.SpringUtils;

import java.util.Collection;
import java.util.List;

/**
 * 传感器工具类
 *
 * @author ruoyi
 */
public class SensorUtils {
    /**
     * 分隔符
     */
    public static final String SEPARATOR = ",";

    /**
     * 设置传感器缓存
     *
     * @param key        参数键
     * @param sensorList 传感器数据列表
     */
    public static void setSensorCache(String key, List<AppSensor> sensorList) {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key), sensorList);
    }

    /**
     * 设置传感器缓存
     *
     * @param key        参数键
     */
    public static void delSensorCache(String key) {
        SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key));
    }

    /**
     * 获取传感器缓存
     *
     * @param key 参数键
     * @return sensorList 传感器数据列表
     */
    public static List<AppSensor> getSensorCache(String key) {
        JSONArray arrayCache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
        if (StringUtils.isNotNull(arrayCache)) {
            return arrayCache.toList(AppSensor.class);
        }
        return null;
    }

    /**
     * 根据传感器ID获取传感器
     *
     * @param sensorId 传感器ID
     * @return 传感器
     */
    public static AppSensor getSensorBySensorId(Long sensorId) {
        AppSensor appSensor = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey("sensorId:") + sensorId);
        if (StringUtils.isNotNull(appSensor)) {
            return appSensor;
        }
        return null;
    }

    public static void setSensorBySensorId(AppSensor appSensor) {
        SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey("sensorId:") + appSensor.getSensorId(), appSensor);
    }

    /**
     * 删除指定传感器缓存
     *
     * @param key 传感器键
     */
    public static void removeSensorCache(String key) {
        SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey("sensorId:") + key);
    }

    /**
     * 清空传感器缓存
     */
    public static void clearSensorCache() {
        Collection<String> keys = SpringUtils.getBean(RedisCache.class).keys(CacheConstants.APP_SENSOR_KEY + "*");
        SpringUtils.getBean(RedisCache.class).deleteObject(keys);
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getCacheKey(String configKey) {
        return CacheConstants.APP_SENSOR_KEY + configKey;
    }
}
